package com.hjw.httpclient.postdemo;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hjw.httpclient.pojo.request.UserRequest;
import org.apache.http.Consts;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.junit.Test;
import org.springframework.http.HttpStatus;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;

/**
 * 模拟发送 application/json 类型的POST请求
 *
 * @author hjwStrart
 * @time 2022-11-20 19:08
 * @version: 1.0
 */
public class Demo2 {

    @Test
    public void method() throws Exception {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse httpResponse = null;
        try {
            httpClient = HttpClients.createDefault();
            String urlStr = "http://localhost:8080/form/testJson";
            URIBuilder uriBuilder = new URIBuilder(urlStr);
            HttpPost httpPost = new HttpPost(uriBuilder.build());

            /* 不行
                ArrayList<NameValuePair> list = new ArrayList<>();
                list.add(new BasicNameValuePair("userName","admin"));
                list.add(new BasicNameValuePair("userPwd","123123"));
                UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(list, Consts.UTF_8);
                httpPost.setEntity(formEntity);
            */
            ObjectMapper objectMapper = new ObjectMapper();
            String jsonStr = objectMapper.writeValueAsString(UserRequest.builder()
                    .userName("admin")
                    .userPwd("123123")
                    .build());
            System.out.println(jsonStr);
            // 第一个参数：json字符串，传递给服务端的json字符串
            StringEntity stringEntity = new StringEntity(jsonStr, Consts.UTF_8);
            // 设置 entity 请求类型
            stringEntity.setContentType(new BasicHeader("Content-Type","application/json;charset=utf-8"));
            // stringEntity.setContentType("application/json;charset=utf-8"); //等价于上述代码
            // 设置 entity 的编码格式
            stringEntity.setContentEncoding(Consts.UTF_8.name());
            httpPost.setEntity(stringEntity);

            httpResponse = httpClient.execute(httpPost);

            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.OK.value()) {
                System.out.println("请求成功");
            }

        } finally {
            if (httpClient != null) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (httpResponse != null) {
                try {
                    httpResponse.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
